/**
 * 搜索功能模块
 */
function initSearch() {
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.querySelector('.search-btn');
    const searchResults = document.getElementById('search-results');
    
    if (!searchInput || !searchBtn || !searchResults) {
        console.warn('搜索相关元素未找到');
        return;
    }
    
    // 为搜索按钮添加点击事件
    searchBtn.addEventListener('click', function() {
        performSearch();
    });
    
    // 防抖函数，用于优化实时搜索性能
    let searchTimeout;
    const debounceSearch = function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            performSearch();
        }, 200); // 200毫秒延迟
    };
    
    // 为搜索输入框添加键盘事件，实现实时搜索
    searchInput.addEventListener('input', function() {
        debounceSearch();
    });
    
    searchInput.addEventListener('keyup', function(e) {
        if (e.key === 'Escape') {
            // 按下ESC键清空搜索框并隐藏搜索结果
            searchInput.value = '';
            searchResults.innerHTML = '';
            searchResults.classList.remove('show');
        }
    });
    
    // 点击页面其他地方关闭搜索结果
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.search-container') && !e.target.closest('#search-results')) {
            searchResults.classList.remove('show');
        }
    });
    
    // 实现搜索功能
    function performSearch() {
        const searchTerm = searchInput.value.trim().toLowerCase();
        
        if (!searchTerm) {
            searchResults.innerHTML = '';
            searchResults.classList.remove('show');
            return;
        }
        
        console.log('搜索关键词：', searchTerm);
        
        // 加载网站和项目数据进行搜索
        Promise.all([
            fetch('./data/websites.json').then(r => r.json()),
            fetch('./data/projects.json').then(r => r.json())
        ]).then(([websitesData, projectsData]) => {
            const allResults = [];
            
            // 搜索网站数据
            if (websitesData && websitesData.categories) {
                websitesData.categories.forEach(category => {
                    if (category.items) {
                        category.items.forEach(website => {
                            if (isMatch(website, searchTerm)) {
                                allResults.push({
                                    type: 'website',
                                    name: website.name,
                                    description: website.description,
                                    url: website.url,
                                    favicon: website.favicon,
                                    category: category.title
                                });
                            }
                        });
                    }
                });
            }
            
            // 搜索项目数据
            if (projectsData && projectsData.categories) {
                projectsData.categories.forEach(category => {
                    if (category.items) {
                        category.items.forEach(project => {
                            if (isMatch(project, searchTerm)) {
                                allResults.push({
                                    type: 'project',
                                    name: project.name,
                                    description: project.description,
                                    url: project.url,
                                    favicon: project.favicon,
                                    category: category.title
                                });
                            }
                        });
                    }
                });
            }
            
            // 显示搜索结果
            displaySearchResults(allResults);
        }).catch(error => {
            console.error('搜索时出错：', error);
            searchResults.innerHTML = '<div class="search-no-results">搜索时出错，请稍后重试</div>';
            searchResults.classList.add('show');
        });
    }
    
    // 汉字转拼音的简单实现（简化版，实际项目中可使用pinyin.js等库）
    function chineseToPinyin(str) {
        // 这个映射表只是一个简化版，实际项目中建议使用完整的拼音库
        const pinyinMap = {
            '豆': 'dou', '包': 'bao', '微': 'wei', '信': 'xin', '腾': 'teng', '讯': 'xun',
            '百': 'bai', '度': 'du', '阿': 'a', '里': 'li', '云': 'yun', '京': 'jing',
            '东': 'dong', '美': 'mei', '团': 'tuan', '头': 'tou', '条': 'tiao', '小': 'xiao',
            '红': 'hong', '书': 'shu', '抖': 'dou', '音': 'yin', '快': 'kuai', '手': 'shou',
            '网': 'wang', '站': 'zhan', '项': 'xiang', '目': 'mu', '工': 'gong', '具': 'ju'
            // 可以根据实际需求扩展更多汉字
        };
        
        let pinyin = '';
        let firstLetters = '';
        
        for (let i = 0; i < str.length; i++) {
            const char = str.charAt(i);
            if (pinyinMap[char]) {
                pinyin += pinyinMap[char];
                firstLetters += pinyinMap[char].charAt(0);
            } else if (/[a-zA-Z0-9]/.test(char)) {
                pinyin += char.toLowerCase();
                firstLetters += char.toLowerCase();
            } else {
                // 保留其他字符，但不加入首字母
                pinyin += char;
            }
        }
        
        return {
            fullPinyin: pinyin,
            firstLetters: firstLetters
        };
    }

    // 判断项目或网站是否匹配搜索关键词，支持高级模糊搜索
    function isMatch(item, searchTerm) {
        // 将搜索关键词标准化（去除空白字符）
        const normalizedSearchTerm = searchTerm.trim().toLowerCase();
        
        // 检查名称匹配
        if (item.name) {
            const normalizedName = item.name.toLowerCase().trim();
            
            // 1. 直接包含搜索词
            if (normalizedName.includes(normalizedSearchTerm)) {
                return true;
            }
            
            // 2. 拼音匹配
            const namePinyin = chineseToPinyin(normalizedName);
            
            // 2.1 完整拼音匹配
            if (namePinyin.fullPinyin.includes(normalizedSearchTerm)) {
                return true;
            }
            
            // 2.2 拼音首字母匹配
            if (namePinyin.firstLetters.includes(normalizedSearchTerm)) {
                return true;
            }
            
            // 3. 检查汉字中包含的字母数字模糊匹配
            const nameLettersNumbers = normalizedName.replace(/[^a-z0-9]/g, '');
            const searchLettersNumbers = normalizedSearchTerm.replace(/[^a-z0-9]/g, '');
            
            if (searchLettersNumbers && nameLettersNumbers.includes(searchLettersNumbers)) {
                return true;
            }
        }
        
        // 检查描述匹配（同样的逻辑）
        if (item.description) {
            const normalizedDescription = item.description.toLowerCase().trim();
            
            if (normalizedDescription.includes(normalizedSearchTerm)) {
                return true;
            }
            
            const descPinyin = chineseToPinyin(normalizedDescription);
            
            if (descPinyin.fullPinyin.includes(normalizedSearchTerm)) {
                return true;
            }
            
            if (descPinyin.firstLetters.includes(normalizedSearchTerm)) {
                return true;
            }
            
            const descLettersNumbers = normalizedDescription.replace(/[^a-z0-9]/g, '');
            const searchLettersNumbers = normalizedSearchTerm.replace(/[^a-z0-9]/g, '');
            
            if (searchLettersNumbers && descLettersNumbers.includes(searchLettersNumbers)) {
                return true;
            }
        }
        
        return false;
    }
    
    // 显示搜索结果
    function displaySearchResults(results) {
        if (results.length === 0) {
            searchResults.innerHTML = '<div class="search-no-results">未找到匹配的内容</div>';
        } else {
            let html = '';
            
            // 按类型分组结果
            const websites = results.filter(item => item.type === 'website');
            const projects = results.filter(item => item.type === 'project');
            
            // 添加网站结果
            if (websites.length > 0) {
                html += '<div style="margin-bottom: 8px;"><span style="color: var(--white-30); font-size: 14px;">网站</span></div>';
                websites.forEach(website => {
                    html += `
                        <div class="search-result-item">
                            <a href="${website.url}" target="_blank">
                                <img src="${website.favicon}" alt="${website.name}">
                                <div>
                                    <h3>${website.name}</h3>
                                    <p>${website.description} <span style="color: var(--white-30); font-size: 12px;">[${website.category}]</span></p>
                                </div>
                            </a>
                        </div>
                    `;
                });
            }
            
            // 添加项目结果
            if (projects.length > 0) {
                html += '<div style="margin: 12px 0 8px;"><span style="color: var(--white-30); font-size: 14px;">项目</span></div>';
                projects.forEach(project => {
                    html += `
                        <div class="search-result-item">
                            <a href="${project.url}" target="_blank">
                                <img src="${project.favicon}" alt="${project.name}">
                                <div>
                                    <h3>${project.name}</h3>
                                    <p>${project.description} <span style="color: var(--white-30); font-size: 12px;">[${project.category}]</span></p>
                                </div>
                            </a>
                        </div>
                    `;
                });
            }
            
            searchResults.innerHTML = html;
        }
        
        searchResults.classList.add('show');
    }
}